/**
* 团队管理
*/
import React, { Component } from 'react';
import { View, StyleSheet, Text, Image, TouchableOpacity, FlatList, DeviceEventEmitter } from "react-native";
import { connect } from 'react-redux';
import { create_service } from '../../redux/index.js';
import { Contract } from '../../service/index.js';
import { Colors, Dimens, ImageRes } from '../../utils/Assets';
import { ProgressView } from '../custom/index'
import { Actions } from 'react-native-router-flux';
import ScrollableTabView from 'react-native-scrollable-tab-view'
import { getStore } from '../../redux/index.js';
class TeamWeeklyTeamDataView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            tabbarName: ['每月', '每天'],
            searchMonth: "",
            searchTime: '',
            currentIndex: 0
        }
        this.userInfo = getStore().getState().auth.userInfo
    }

    componentDidMount() {
        this.listener = DeviceEventEmitter.addListener('ChangeIndex', (value) => {
            this.setState({ currentIndex: value.index })
        })
    }
    componentWillUnmount() {
        this.listener && this.listener.remove()
    }
    goSelectTime() {
        let date = new Date();
        date.setTime(date.getTime());
        Actions.commonDatePicker({
            defaultDate: this.getDefaultTime(),
            endYear: date.getFullYear(),
            endMonth: date.getMonth() + 1,
            endDay: date.getDate(),
            shoDay: true,
            modalCallback: (dateStr) => {
                this.setState({ searchTime: dateStr })
            }
        });
    }
    goSelectMonth() {
        let date = new Date();
        date.setTime(date.getTime());
        Actions.commonDatePicker({
            defaultDate: this.getDefaultTime(),
            endYear: date.getFullYear(),
            endMonth: date.getMonth() + 1,
            endDay: date.getDate(),
            shoDay: false,
            modalCallback: (dateStr) => {
                this.setState({ searchMonth: dateStr })
            }
        });
    }
    getDefaultTime() {
        let date = new Date();
        date.setTime(date.getTime())
        let year = date.getFullYear()
        let month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : ("0" + (date.getMonth() + 1))
        let day = date.getDate() > 9 ? date.getDate() : ("0" + date.getDate())
        return year + "-" + month + "-" + day
    }
    render() {
        return (
            <View style={styles.container}>
                <View style={styles.nav}>
                    <TouchableOpacity style={{ justifyContent: 'center', flex: 1 }} activeOpacity={0.8} onPress={() => {
                        Actions.pop()
                    }}>
                        <Image source={ImageRes.icon_back} style={{ width: 30, height: 30, marginLeft: 10 }}></Image>
                    </TouchableOpacity>
                    <View style={{ flex: 1, justifyContent: 'center' }}>
                        <Text style={{ color: '#333333', fontSize: 18, alignSelf: 'center', fontWeight: 'bold', alignSelf: 'center' }}>团队数据</Text>
                    </View>
                    <View style={{ flex: 1, justifyContent: 'flex-end', flexDirection: 'row' }}>
                        <TouchableOpacity style={{ justifyContent: 'center', marginRight: 15 }} onPress={() => {
                            if (this.state.currentIndex == 0) {
                                this.goSelectMonth()
                            } else {
                                this.goSelectTime()
                            }
                        }}>
                            <Image style={{ width: 20, height: 22, alignSelf: 'flex-end' }} source={ImageRes.profit_daily}></Image>
                        </TouchableOpacity>
                    </View>
                </View>
                <ScrollableTabView
                    locked={true}
                    renderTabBar={() => <TabBar />}>
                    {
                        this.state.tabbarName.map((item, index) => {
                            return (
                                <SubView key={index} tabLabel={item} index={index} dispatch={this.props.dispatch} userInfo={this.userInfo} users_id={this.props.users_id} searchTime={this.state.searchTime} searchMonth={this.state.searchMonth} />
                            )
                        })
                    }
                </ScrollableTabView>
                <ProgressView show={this.state.loading} />
            </View>
        )
    }
}
class SubView extends Component {
    constructor(props) {
        super(props)
        this.state = {
            listData: [],
            refreshing: false,
            loading: false
        }
        this.pageSize = 10
        this.page = 1
        this.titleArr = ['类型', '直营', '团队', '总额']
    }
    componentDidMount() {
        this.getListData(true)
    }
    componentWillReceiveProps(nextProps) {
        if (this.props.searchTime != nextProps.searchTime || this.props.searchMonth != nextProps.searchMonth) {
            this.setState({ searchTime: nextProps.searchTime, searchMonth: nextProps.searchMonth }, () => {
                this.getListData(true)
            })
        }
    }
    getListData(refresh) {
        if (refresh) {
            this.setState({ refreshing: true })
        } else {
            this.setState({ loading: true })
        }
        let params = {
            token: this.props.userInfo.token,
            page: this.page,
            pageSize: this.pageSize,
            group: this.props.index == 0 ? 'month' : 'date',
            users_id: this.props.users_id,
        }
        if (this.props.index == 0 && this.state.searchMonth) {
            params.date = this.state.searchMonth
        }
        if (this.props.index == 1 && this.state.searchTime) {
            params.date = this.state.searchTime
        }
        this.setState({ loading: true })
        this.props.dispatch(create_service(Contract.POST_USER_COUNT, params))
            .then(res => {
                if (res && res.list) {
                    for (let index = 0; index < res.list.length; index++) {
                        res.list[index].valueArr = ['团队数据', res.list[index].direct_user_number, res.list[index].team_user_number, res.list[index].user_number]
                    }
                    if (refresh) {
                        this.setState({ listData: res.list, pagination: res.pagination, loading: false, refreshing: false })
                    } else {
                        this.setState({ listData: this.state.listData.concat(res.list), pagination: res.pagination, loading: false, refreshing: false })
                    }
                }
            })
    }
    renderItem({ item, index }) {
        return (
            <View style={{ backgroundColor: "#ffffff", marginHorizontal: 15, borderRadius: 10 }}>
                <Text style={{ fontSize: 16, color: "#378EFB", marginTop: 15, marginLeft: 15 }}>{item.date}</Text>
                <View style={{ marginTop: 15, height: 1, backgroundColor: Colors.bg_color, marginHorizontal: 15 }}></View>
                <View style={{ flexDirection: 'row' }}>
                    {this.titleArr.map((value, index) => {
                        return (
                            <View style={{ flex: 1, justifyContent: 'center', paddingVertical: 15 }} key={index}>
                                <Text style={{ fontSize: 15, color: "#999999", alignSelf: 'center' }}>{value}</Text>
                            </View>
                        )
                    })}
                </View>
                <View style={{ height: 1, backgroundColor: Colors.bg_color, marginHorizontal: 15 }}></View>
                <View style={{ flexDirection: 'row' }}>
                    {item.valueArr.map((value, index) => {
                        return (
                            <View style={{ flex: 1, justifyContent: 'center', paddingVertical: 15 }} key={index}>
                                <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center' }}>{value}</Text>
                            </View>
                        )
                    })}
                </View>
            </View>
        )
    }
    render() {
        return (
            <View style={{ flex: 1 }}>
                {(!this.listData || this.listData.length == 0) && this.finishRequest ? <View style={{ flex: 1, backgroundColor: Colors.white_color }}>
                    <Image source={ImageRes.personal_icon_no_trade} style={{ width: Dimens.DeviceWidth - 120, height: (Dimens.DeviceWidth - 120) * 0.8, alignSelf: 'center', marginTop: 50, resizeMode: 'contain' }}></Image>
                    <Text style={{ fontSize: 16, color: Colors.textCommonGray, alignSelf: 'center', marginTop: 30 }}>暂无数据</Text>
                </View> : <FlatList
                        ref={(list) => (this.flatList = list)}
                        keyExtractor={(item, index) => index.toString()}
                        data={this.state.listData}
                        ItemSeparatorComponent={() => <View style={{ backgroundColor: Colors.bg_color, height: 10 }} />}
                        showsVerticalScrollIndicator={false}
                        renderItem={this.renderItem.bind(this)}
                        style={{ marginVertical: 15 }}
                    />}
                <ProgressView show={this.state.loading} />
            </View>
        )
    }
}
const TabBar = (props) => {
    let { tabs, activeTab, goToPage } = props;
    return (
        <View style={{ backgroundColor: Colors.white_color, width: Dimens.DeviceWidth, height: 50, flexDirection: 'row' }}>
            {tabs.map((tab, i) => (
                <TouchableOpacity onPress={() => {
                    goToPage(i)
                    DeviceEventEmitter.emit('ChangeIndex', { index: i })
                }} activeOpacity={0.8} key={i} style={{ flex: 1, height: 50, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 15, backgroundColor: Colors.white_color }}>
                    <View style={{ flexDirection: 'row' }}>
                        <Text style={{ color: (activeTab == i ? '#378EFB' : "#333333"), fontSize: 14, alignSelf: 'center' }}>{tab}</Text>
                    </View>
                    <View style={{ width: 100, height: 3, backgroundColor: (activeTab == i ? "#378EFB" : 'transparent'), position: 'absolute', bottom: 0, alignSelf: 'center' }} />
                </TouchableOpacity>
            ))}
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Colors.bg_color,
    },
    nav: {
        height: Dimens.isAndroid ? 44 : (Dimens.isIPhoneX ? 88 : 64),
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingTop: Dimens.isAndroid ? 0 : (Dimens.isIPhoneX ? 44 : 20)
    }
});
const ExportView = connect()(TeamWeeklyTeamDataView);
module.exports.TeamWeeklyTeamDataView = ExportView
